package com.project.util.validation;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ExistValidator implements ConstraintValidator<Exist, String> {
    @Autowired
    private SqlSession sqlSession;
    private String sqlId;

    @Override
    public void initialize(Exist exist) {
        this.sqlId = exist.sqlId();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        if (str.length() > 0) {
            Object record = sqlSession.selectOne(sqlId,str);
            if (record == null) {
                return true;
            }
        }
        else {
            constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值
            //重新添加错误提示语句
            constraintValidatorContext.buildConstraintViolationWithTemplate("").addConstraintViolation();
        }
        return false;
    }
}
